class RewardsController < ApplicationController
  before_filter :require_officer, :except => [ :index, :show ]
  
  def show
    @reward = Reward.find(params[:id])
    @classes = CharacterClass.find(:all)
    @characters_of_class = { }
    @classes.each { |c|
      @characters_of_class[c] = (@reward.characters.collect { |char| char if char.character_class_id == c.id }).compact
    }

    if @reward.comment.length > 0
      @page_description = @reward.comment
    elsif @reward.mob
      @page_description = @reward.mob.name
    else
      @page_description = "Reward #{@reward.id}"
    end
  end

  def edit
    @page_description = "Edit reward"
    @reward = Reward.find(params[:id])

    if flash[:characters]
      @character_list = flash[:characters][:list]
    else
      @character_list = @reward.characters.collect { |c| c.name }.join("\n")
    end
  end

  def update
    @reward = Reward.find(params[:id])
    if params[:characters][:list]
      rewarded_characters, unknown_characters, error_string = parse_character_list(params[:characters][:list])
      
      if unknown_characters.length > 0
        flash[:notice] = error_string
        flash[:characters] = params[:characters]
        redirect_to :action => :edit, :id => params[:id]
      else
        Reward.transaction do
          @reward.update_attributes(params[:reward])
          CharactersReward.transaction do
            CharactersReward.find(:all, :conditions => [ "reward_id = ?", @reward.id ]).each { |rc|
              rc.destroy
            }
            rewarded_characters.uniq.each { |c| c.save }
          end
          @reward.save
        end
        expire_fragment("characters/dkp_table")
        flash[:notice] = "Reward updated."
        redirect_to :controller => "raids", :action => :edit, :id => @reward.raid.id
      end
    end
  end

  def create
    @raid = Raid.find(params[:raid_id])
    @reward = Reward.new(params[:reward])

    if @reward.save
      flash[:notice] = "Edit new reward."
      redirect_to :action => :edit, :id => @reward.id
    end
  end
  
  private
  def parse_character_list(list)
    rewarded_characters = [ ]
    unknown_characters = [ ]
    error_string = ""
    if params[:characters][:list]
      params[:characters][:list].each { |name|
        next if (name =~ /^\W*$/)  # ignore empty lines
        name = name.chomp
        c = Character.find(:first, :conditions => [ "name = ?",  name ])
        if c == nil
          unknown_characters << name
          next
        end
        r = CharactersReward.new(:reward => @reward, :character => c)
        rewarded_characters << r
      }
    end
    if unknown_characters.length > 0
       characters = "character"
       characters = characters.pluralize if unknown_characters.length > 1
       error_string = "Unknown #{characters} '#{unknown_characters.join('\', \'')}'.\n"
    end
    return rewarded_characters, unknown_characters, error_string
  end
    
end
